<template>
    <el-image-viewer v-if="viewerVisible" 
    :url-list="HignSpeedUrls"
    :initial-index="imgcurrentIndex" 
    @close="closeViewerimg" />
    <el-drawer
        v-model="isShow"
        size="50%"
        :destroy-on-close="true"
        @close="closeHandle"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
    <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
        </template>
    <el-form :model="form"  ref="formRef" :rules="rules" v-loading="loading">
        <el-row class="mb-4" :gutter="20">
            <el-col :span="12">
                <el-form-item label="涉案人" required label-width="80px">
                    <el-input v-model="user_name" :readonly="true"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
            <el-col :span="12">
                <el-form-item label="体检医生" required label-width="80px" prop="examusername">
                    <el-input v-model="form.examusername" :readonly="isreadonly"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="体检时间" required label-width="80px" prop="examdate">
                    <el-date-picker
                    v-model="form.examdate"
                    type="datetime"
                    placeholder="请选择安检时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width:100%"
                    :readonly="isreadonly"
                />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="体检地点" label-width="80px">
                    <el-input v-model="form.examplace" :readonly="isreadonly"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="体检原因" label-width="80px">
                    <el-input v-model="form.examreason" :readonly="isreadonly"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="体温" label-width="80px">
                    <el-input v-model="form.temperature"  :readonly="isreadonly"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="血压" label-width="80px">
                    <el-input v-model="form.blood" :readonly="isreadonly" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="心率" label-width="80px">
                    <el-input v-model="form.heartrate" :readonly="isreadonly" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="呼吸" label-width="80px">
                    <el-input v-model="form.breathing" :readonly="isreadonly" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="既往病史及目前处置情况" label-position="top" label-width="180px">
                    <el-input v-model="form.medicalhistory" type="textarea" :rows="3" :readonly="isreadonly"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="体检情况及意见" label-position="top" required prop="examdetail">
                    <el-input v-model="form.examdetail" type="textarea" :rows="3" :readonly="isreadonly" />
                </el-form-item>
            </el-col>
            <el-col :span="12" class="qianming">
                <el-form-item label="医生签字">
                    <div class="demo-image__error">
                        <el-image style="width: 110px; height: 110px;"  
                        :src="DocSignUrl" 
                        fit="contain"
                        :preview-src-list="srcListDoc"
                        :preview-teleported='true'>
                            <template #error>
                                <div class="image-slot">
                                    请签字
                                </div>
                            </template>
                        </el-image>
                    </div>
                    <template v-if="isShowSignBtn">
                        <el-button type="primary" @click="DocSignBtn" v-if="DocSignUrl ==''" :disabled="isbackmsg">签字</el-button>
                        <el-button type="primary" @click="DocResignBtn" v-else  :disabled="isbackmsg">重签</el-button>
                    </template>
                </el-form-item>
            </el-col>
            <el-col :span="12" class="qianming">
                <el-form-item label="涉案人签字">
                    <div class="demo-image__error">
                        <el-image style="width: 110px; height: 110px;" 
                        :src="SarSignUrl" 
                        fit="contain" 
                        :preview-src-list="srcListSar"
                        :preview-teleported='true'>
                            <template #error>
                                <div class="image-slot">
                                    请签字
                                </div>
                            </template>
                        </el-image>
                    </div>
                    <template v-if="isShowSignBtn">
                        <el-button type="primary" @click="SarSignBtn" v-if="SarSignUrl ==''" :disabled="isbackmsg">签字</el-button>
                        <el-button type="primary" @click="SaeResignBtn" v-else :disabled="isbackmsg">重签</el-button>
                    </template>
                    
                </el-form-item>
            </el-col>
            <el-col :span="24" class="mt-2">
                <el-row style="width: 100%;" v-if="isShowSignBtn">
                    <el-col :span="10" >
                        <el-button v-if="isopenCameraBtn"  type="primary" @click="CameraBtn" class='mb-3'>
                            启动摄像头
                        </el-button>
                        <el-button v-else type="danger" @click="CloseCameraBtn" class='mb-3'>
                            关闭摄像头
                        </el-button>
                        <!-- <el-button   type="primary" @click="CameraBtn" class='mb-3'>
                            启动摄像头
                        </el-button>
                        <el-button  type="danger" @click="CloseCameraBtn" class='mb-3'>
                            关闭摄像头
                        </el-button> -->
                    </el-col>
                    <el-col :span="12">
                        <el-button v-if="!isopenCameraBtn" type="primary" @click="SaveCameraBtn" class='mb-3'>
                            拍照
                        </el-button>
                    </el-col>
                </el-row>
              <el-row style="width: 100%;" v-if="isShowSignBtn">
                  <el-col :span="22">
                      <div style="width: 422px;height: 302px;border: 1px solid #666666; background: #fff">
                          <canvas ref="videoCanvas" width="420" height="300"></canvas>
                      </div>
                  </el-col>
              </el-row>
              <el-col :span="24" style="display: flex;flex-wrap: wrap;">
                <div class="block" style="width: 110px; height: 110px;position: relative;margin-right: 10px;"
                    v-for="(img, index) in HignSpeedUrls"  @click="clickImage(index)"
                    :key="index">
                    <el-image style="width: 110px; height: 110px;position: relative;"
                      :src="img"
                      fit="contain" 
                      >
                        <template #error>
                            <div class="image-slot">
                                请使用高拍仪
                            </div>
                        </template>
                    </el-image>
                    <el-icon class="me-1 edit-icon" @click="deletHighSpeedImg(index, $event)">
                        <circle-close />
                    </el-icon>
                </div>
              </el-col>
            </el-col>
        </el-row>
    </el-form>
    <template #footer>
        <el-button type="primary" v-if="!isreadonly" @click="Confirm">确认</el-button>
        <el-button @click="closeConfirm">关闭</el-button>
    </template>
    </el-drawer>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { ElImageViewer } from 'element-plus'
import {getCurrentInstance} from "vue";
const {proxy} = getCurrentInstance()

import { WebSocketService } from "@/utils/websocket";  // 导入 WebSocket 服务

import { getPoliceAreaInfo } from "@/api/PoliceAreaManage/PoliceAreaManage";

import {SignuploadFile,SignDelFile,SignList,SignimageInfo} from "@/api/ApplyDetail/ApplyDetail";

import {PhysicalexaminationAdd,PhysicalexaminationInfo,PhysicalexaminationEdit} from "@/api/ApplyDetail/ApplyDetail";
const {nj_sex,nj_sheanren_type,nj_sheanren_status} = proxy.useDict( 'nj_sex','nj_sheanren_type','nj_sheanren_status')

const isShow = ref(false)
const isShowSignBtn = ref(true)

const loading = ref(false)
const isreadonly = ref(false)
const user_name = ref('')

const isbackmsg = ref(false)

const isopenCameraBtn = ref(true) // 摄像头按钮是否显示

// 新增帧率控制相关变量
const targetFPS = 20; // 目标帧率(可根据需要调整)1秒15帧。可以调整，越高越流畅，但是对内存及  Gpu要求越高
const frameInterval = 1000 / targetFPS; // 每帧间隔(ms)
let lastRenderTime = 0; // 上次渲染时间戳
let frameQueue = []; // 帧队列(最多保留1帧)
let isRendering = false; // 是否正在渲染中
let animationFrameId = null; // requestAnimationFrame ID


const videoCanvas = ref(null); // Canvas DOM 引用
const canvasCtx = ref(null);   // Canvas 2D 上下文


// WebSocket 服务实例
let webSocketService = null;
const websocketUrl = ref()

const viewerVisible = ref(false)
const imgcurrentIndex = ref(0);

// 用于关闭预览
const clickImage = (index) => {
  imgcurrentIndex.value = index
    setTimeout(() => {
        viewerVisible.value = true;
    }, 100);
};
// 用于关闭预览
const closeViewerimg = () => {
  viewerVisible.value = false;
};

const srcListDoc = ref([])
const srcListSar = ref([])
const DocSignUrl = ref('')
const SarSignUrl = ref('')
const SignType = ref('1')   //签字类型。1为医生签字，2为涉案人签字
const isHighSpeedValue = ref(1)   //是否为高拍仪。1为签字，2为高拍仪

const HignSpeedSubUploadID = ref([])
const HignSpeedUrls = ref([])


const DocSignUploadId = ref()
const SarSignUploadId = ref()

const title = ref('新增体检记录')
const form = ref({
    fileList:[]
})
const changeShowStatus = () => {
    isShow.value = !isShow.value
}
const rules = {
    examusername: [{ required: true, message: "体检医生不能为空", trigger: "blur" }],
    examdate: [{ required: true, message: "体检时间不能为空", trigger: "blur" }],
    examdetail: [{ required: true, message: "检查情况不能为空", trigger: "blur" }],
    
}

// 通知事件
const emit = defineEmits(['getList'])
onMounted(() => {
    // 获取个人信息-获取到当前登录者的所在单位，然后用单位去获取办案区的IP地址
    window.addEventListener('beforeunload', cleanup);
    nextTick(() => {
        
    })
})

// 获取详情
const getInfo = async (jwApplydetailId) => {
    await PhysicalexaminationInfo(jwApplydetailId).then(res => {
      form.value = res.data
      loading.value = false
    })
}
const showAdd = async (jwApplydetailId,data) => {
    changeShowStatus()
    setTimeout(() => {
        if (videoCanvas.value) {
            canvasCtx.value = videoCanvas.value.getContext('2d');
            videoCanvas.value.width = 420;
            videoCanvas.value.height = 300;
            console.log("Canvas初始化完成，尺寸:", videoCanvas.value.width, "x", videoCanvas.value.height);
        } else {
            console.error("Canvas元素未找到！");
        }
    }, 300);
    
    console.log(data)
    getPoliceAreaInfos(data)
    HignSpeedUrls.value = []
    isShowSignBtn.value = true
    isbackmsg.value = false
    user_name.value = data.user_name
    form.value.jwApplydetailId = jwApplydetailId
    
    const HighSpeedSignQuery = {objectId:data.jw_applydetail_id,type:3 }
    const DocSignQuery = {objectId:data.jw_applydetail_id,type:4 }
    const SarSignQuery = {objectId:data.jw_applydetail_id,type:5 }
    SignList(HighSpeedSignQuery).then(res => {
        HignSpeedUrls.value = []
        HignSpeedSubUploadID.value = []
        for(var i = 0;i<res.data.length;i++){
            HignSpeedSubUploadID.value[i] = res.data[i].jwUploadId
            const fileType = res.data[i].filename.split('.')[1]
            SignimageInfo(res.data[i].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                HignSpeedUrls.value.push(BlobUrlListData);
            })
        }
    })
    SignList(DocSignQuery).then(res => {
        if(res.data.length > 0){
            DocSignUploadId.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                DocSignUrl.value = BlobUrlListData
                srcListDoc.value[0] = BlobUrlListData
            })
        }
        
    })
    SignList(SarSignQuery).then(res => {
        if(res.data.length > 0){
            SarSignUploadId.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
            const blob = new Blob([res], { type: 'image/' + fileType });
            const BlobUrlListData = URL.createObjectURL(blob);
            SarSignUrl.value = BlobUrlListData
            srcListSar.value[0] = BlobUrlListData
            })
        }
        
    })
}

const showEdit = async (data,isSee,propdata) => {
    changeShowStatus()
    setTimeout(() => {
        if (videoCanvas.value) {
            canvasCtx.value = videoCanvas.value.getContext('2d');
            videoCanvas.value.width = 420;
            videoCanvas.value.height = 300;
            console.log("Canvas初始化完成，尺寸:", videoCanvas.value.width, "x", videoCanvas.value.height);
        } else {
            console.error("Canvas元素未找到！");
        }
    }, 300);
    if(isSee == 'See'){
        title.value = '就医体检详情'
        isreadonly.value = true
        loading.value = true
        isShowSignBtn.value = false
        user_name.value = propdata.user_name
        getInfo(data.jw_physicalexamination_id)
    }else{
        title.value = '就医体检编辑'
        isreadonly.value = false
        loading.value = true
        isShowSignBtn.value = true
        user_name.value = propdata.user_name
        getInfo(data.jw_physicalexamination_id)
    }
    getPoliceAreaInfos(propdata)
    isbackmsg.value = false
    const HighSpeedSignQuery = {objectId:data.jw_applydetail_id,type:3 }
    const DocSignQuery = {objectId:data.jw_applydetail_id,type:4 }
    const SarSignQuery = {objectId:data.jw_applydetail_id,type:5 }
    SignList(HighSpeedSignQuery).then(res => {
        HignSpeedUrls.value = []
        HignSpeedSubUploadID.value = []
        for(var i = 0;i<res.data.length;i++){
            HignSpeedSubUploadID.value[i] = res.data[i].jwUploadId
            const fileType = res.data[i].filename.split('.')[1]
            SignimageInfo(res.data[i].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                HignSpeedUrls.value.push(BlobUrlListData);
            })
        }
    })
    SignList(DocSignQuery).then(res => {
        if(res.data.length > 0){
            DocSignUploadId.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                DocSignUrl.value = BlobUrlListData
                srcListDoc.value[0] = BlobUrlListData
            })
        }
        
    })
    SignList(SarSignQuery).then(res => {
        if(res.data.length > 0){
            SarSignUploadId.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
            const blob = new Blob([res], { type: 'image/' + fileType });
            const BlobUrlListData = URL.createObjectURL(blob);
            SarSignUrl.value = BlobUrlListData
            srcListSar.value[0] = BlobUrlListData
            })
        }
        
    })
    
}
// 获取办案区ip地址
const getPoliceAreaInfos = async (querydata) => {
    const data = {
        unitId:querydata.policeAreaUnitId,
        areatype:querydata.TYPE
    }
    getPoliceAreaInfo(querydata.policearea_id).then(res => {
        websocketUrl.value = 'ws://' + res.data.ipAddress + ':' + res.data.port
        // 创建 WebSocket 实例
        webSocketService = new WebSocketService(websocketUrl.value);
        // webSocketService = new WebSocketService('ws://192.168.3.34:18887');
        // 启动 WebSocket 连接
        webSocketService.createWebSocket()
        .then(() => {
            const path = window.location.pathname
            const istrue =  path.includes('/PoliceWork/')
            if(isShowSignBtn.value){
                if(istrue){
                ElMessage.success({
                message: '与终端设备连接成功',
                showClose: true,
            })
            }
                // 设置接收到消息时的回调
                webSocketService.setOnMessageCallback(handleWebSocketMessage);
                // 发送消息
                isopenCameraBtn.value = true // 摄像头按钮是否显示
            }
        })
        .catch((error) => {
            ElMessage.error({
            message: '与终端连接失败',
            showClose: true,
            })
        });
        
    })
}
// 确认按钮
const Confirm = async () => {
    form.value.fileList = []
    if (HignSpeedSubUploadID.value.length > 0) {
        form.value.fileList = HignSpeedSubUploadID.value
    }
    if (DocSignUploadId.value) {
        form.value.fileList.push(DocSignUploadId.value);
    }
    if (SarSignUploadId.value) {
        form.value.fileList.push(SarSignUploadId.value);
    }
    
    proxy.$refs["formRef"].validate(valid => {
    if (valid) {
        if(form.value['jwPhysicalexaminationId']){
            loading.value = true
            PhysicalexaminationEdit(form.value).then(res => {
                closewebSocketService()
                loading.value = false
                changeShowStatus()
                emit('getList', '来了老弟')
            })
        } else {
            PhysicalexaminationAdd(form.value).then(res => {
                closewebSocketService()
                loading.value = false
                changeShowStatus()
                proxy.$modal.msgSuccess(`新增成功`)
                emit('getList', '来了老弟')
            })
        }
    }
  });
}

// 医生签字
const DocSignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
    }
    proxy.$modal.msg(`医生签字`)
    isbackmsg.value = true
    SignType.value = '1'
    isHighSpeedValue.value = 1
    websocket()
}
// 医生重新签字
const DocResignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
    }
    SignType.value = '1'
    isHighSpeedValue.value = 1
    isbackmsg.value = true
    if(DocSignUploadId.value == ''){
        return
    }else{
        await SignDelFile(DocSignUploadId.value).then(res => {
            proxy.$modal.msg(`医生重新签字`)
            DocSignUrl.value = ''
            DocSignUploadId.value = ''
            websocket()
        })
    }
    
}
// 涉案人签字
const SarSignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
    }
    SignType.value = '2'
    isHighSpeedValue.value = 1
    isbackmsg.value = true
    proxy.$modal.msg(`涉案人签字`)
    websocket()
}

// 涉案人重新签字
const SaeResignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
    }
    SignType.value = '2'
    isHighSpeedValue.value = 1
    isbackmsg.value = true
    if(SarSignUploadId.value == ''){
        return
    }else{
        await SignDelFile(SarSignUploadId.value).then(res => {
            proxy.$modal.msg(`涉案人重新签字`)
            SarSignUrl.value = ''
            SarSignUploadId.value = ''
            websocket()
        })
    }
    
}
// 发送消息
function SendMes(isHighSpeed) {
    // setTimeout(() => {
    //     webSocketService.sendMessage(isHighSpeed)        //1是签名，2是高拍仪
    // }, 300);
    webSocketService.sendMessage(isHighSpeed)        //1是签名，2是高拍仪，3是身份证
  
}
// 点击启动摄像头
function CameraBtn() {
    isHighSpeedValue.value = 2
    if(webSocketService.ws.readyState == 1){
        webSocketService.sendMessage(2) //1是签名，2是高拍仪，3是身份证
        isopenCameraBtn.value = false // 摄像头按钮是否显示
    }else{
      // 创建 WebSocket 实例
      webSocketService = new WebSocketService(websocketUrl.value);
    //   webSocketService = new WebSocketService('ws://192.168.3.34:18887');
      // 启动 WebSocket 连接
      webSocketService.createWebSocket()
        .then(() => {
        //   ElMessage.success({
        //     message: '与终端设备连接成功',
        //     showClose: true,
        //   })
          // 设置接收到消息时的回调
          webSocketService.setOnMessageCallback(handleWebSocketMessage);
          // 发送消息
          webSocketService.sendMessage(2)
          isopenCameraBtn.value = false // 摄像头按钮是否显示
        })
        .catch((error) => {
          // proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
        });
    }
    
}
// 点击关闭摄像头{
  function CloseCameraBtn() {
    if(webSocketService){
        webSocketService.sendMessage('closeCamera')
        isopenCameraBtn.value = true // 摄像头按钮是否显示
        // 清空画布
        clearCanvas();
    }
}
// 清空画布的函数
function clearCanvas() {
  if (canvasCtx.value && videoCanvas.value) {
    console.log("清空画布")
    // 清除整个画布
    // 强制重绘（备用方案）
    if (canvasCtx.value) {
      canvasCtx.value.clearRect(0, 0, 
        videoCanvas.value.width, 
        videoCanvas.value.height);
    }
    // 可选：填充白色背景（如果需要）
      canvasCtx.value.fillStyle = '#ffffff';
      canvasCtx.value.fillRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
  }
}
// 点击保存图片
async function SaveCameraBtn() {
  webSocketService.sendMessage(11) // 1是签名，2是高拍仪，3是身份证
}
// const HighSpeedBtn = async () => {
//     console.log(webSocketService)
// //   isHighSpeedValue.value = 2
// //   proxy.$modal.msg(`正在启动高拍仪...`)
// //   websocket()
// }
defineExpose({showAdd,showEdit})

// webSocketService建立连接
const websocket = async () =>{
    console.log(webSocketService.ws.readyState)
        if(webSocketService.ws.readyState == 1){
            SendMes(isHighSpeedValue.value)
            isopenCameraBtn.value = false // 摄像头按钮是否显示
        }else{
             // 创建 WebSocket 实例
            // webSocketService = new WebSocketService('ws://192.168.3.34:18887');
            webSocketService = new WebSocketService(websocketUrl.value);
            // 启动 WebSocket 连接
            webSocketService.createWebSocket()
            .then(() => {
                const path = window.location.pathname
                const istrue =  path.includes('/PoliceWork/')
                if(istrue){
                //     ElMessage.success({
                //     message: '与终端设备连接成功',
                //     showClose: true,
                // })
                // 发送消息
                webSocketService.setOnMessageCallback(handleWebSocketMessage);
                SendMes(isHighSpeedValue.value)
                isopenCameraBtn.value = false // 摄像头按钮是否显示
                }
                
            })
            .catch((error) => {
                proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
            });
        }
}

// 处理 WebSocket 消息
function handleWebSocketMessage(message) {
    isbackmsg.value = false
    let imgUrl = ''
    if (message === 'cancel' || message === 'end') {
        proxy.$modal.msgWarning(`用户${message === 'cancel' ? '取消' : '结束'}了操作`);
        return;
    }
    if(isHighSpeedValue.value == '2'){
        // const query = {
        //     jwApplyDetailId:form.value.jwApplydetailId,
        //     md5key:'12313',
        //     fileType:'3'                   //  3体检高拍仪 4体检医生签名 5体检涉案人签名
        // }
        if(typeof message === 'string'){
            try {
                    const data = JSON.parse(message);
                    if (data.photo) {
                        // 处理拍照结果...
                        // 创建Base64图片URL
                    const imgUrl = `data:image/jpeg;base64,${data.photo}`;
                    // 将图片URL添加到HignSpeedUrls数组
                    HignSpeedUrls.value.push(imgUrl);
                    // 2. 转成 Blob（base64 => binary）
                    const byteString = atob(data.photo);
                    const arrayBuffer = new ArrayBuffer(byteString.length);
                    const uint8Array = new Uint8Array(arrayBuffer);
                    for (let i = 0; i < byteString.length; i++) {
                        uint8Array[i] = byteString.charCodeAt(i);
                    }
                    const blob = new Blob([uint8Array], { type: 'image/jpeg' });

                    // 3. 准备上传参数
                    const query = {
                        jwApplyDetailId: form.value.jwApplydetailId,
                        md5key: '12313',
                        fileType: '3' //  3体检高拍仪 4体检医生签名 5体检涉案人签名
                    };

                    const formData = new FormData();
                    formData.append('file', blob, 'capture.jpg');

                    // 4. 调用上传接口
                    SignuploadFile(formData, query).then(res => {
                        proxy.$modal.msgSuccess(`照片上传成功`);
                        HignSpeedSubUploadID.value.push(res.msg);
                    });
                    }
                    return; // 拍照逻辑结束后直接返回
                } catch (e) {
                    console.warn("非JSON消息:", message);
                }
            }
        // 情况2：视频流的Blob数据
        if (message instanceof Blob) {
            if (frameQueue.length > 0) {
                frameQueue[0] = message;
            } else {
                frameQueue.push(message);
            }
            scheduleRender();
        }
    }else{
        // 情况1：签名的Base64数据
        if(SignType.value == '1'){
            imgUrl = message;
            DocSignUrl.value = imgUrl
            srcListDoc.value[0] = imgUrl
            const query = {
                jwApplyDetailId:form.value.jwApplydetailId,
                md5key:'12313',
                fileType:'4'            //  3体检高拍仪 4体检医生签名 5体检涉案人签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                DocSignUploadId.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }else{
            imgUrl = message;
            SarSignUrl.value = imgUrl
            srcListSar.value[0] = imgUrl
            const query = {
                jwApplyDetailId:form.value.jwApplydetailId,
                md5key:'12313',
                fileType:'5'            //  3体检高拍仪 4体检医生签名 5体检涉案人签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                SarSignUploadId.value = res.msg
            }).catch(error => {
                console.error('上传失败', error);
            });
            }
        }
}
// 删除图片
const deletHighSpeedImg = async (index, event) => {
    event.stopPropagation();
    loading.value = true
  await SignDelFile(HignSpeedSubUploadID.value[index]).then(res => {
    loading.value = false
      HignSpeedUrls.value.splice(index, 1);
      HignSpeedSubUploadID.value.splice(index, 1);
      proxy.$modal.msgSuccess(`删除成功`)
  })
}
// 返回的base64数据进行处理-上传
function uploadBase64Image(base64Data, query) {
  // 1. 去掉 Base64 前缀部分（例如 'data:image/png;base64,'）
  const base64Str = base64Data.split(',')[1];
  
  // 2. 将 Base64 字符串转换为二进制数据
  const byteCharacters = atob(base64Str);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset++) {
    const byte = byteCharacters.charCodeAt(offset);
    byteArrays.push(byte);
  }
  // 3. 创建一个 Blob 对象，设置文件类型（如 image/png）
  const byteArray = new Uint8Array(byteArrays);
  const blob = new Blob([byteArray], { type: 'image/png' });
  // 4. 创建 FormData 对象
  const formData = new FormData();
  formData.append('file', blob, 'image.png');  // 这里的 'image.png' 是文件名，你可以根据需要修改
  // 6. 调用接口进行上传
  return SignuploadFile(formData, query);  // 这里传递 formData 和 query
}

// 关闭webSocketService
const closewebSocketService = () => {
  if(webSocketService){
    webSocketService.close()
  }
}
// 新增的调度渲染函数
function scheduleRender() {
    // 如果已经在渲染或队列为空，则跳过
    if (isRendering || frameQueue.length === 0) return;
    
    const now = performance.now();
    const elapsed = now - lastRenderTime;
    
    // 如果还没到下一帧的渲染时间，延迟执行
    if (elapsed < frameInterval) {
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
        }
        animationFrameId = requestAnimationFrame(() => {
            scheduleRender();
        });
        return;
    }
    
    // 执行渲染
    processRender();
}

// 新增的处理渲染函数
function processRender() {
    if (isRendering || frameQueue.length === 0) return;
    
    isRendering = true;
    const blob = frameQueue.shift();
    lastRenderTime = performance.now();
    
    // 使用Blob创建对象URL
    const url = URL.createObjectURL(blob);
    const img = new Image();
    
    img.onload = () => {
        if (canvasCtx.value) {
            canvasCtx.value.clearRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
            canvasCtx.value.drawImage(
                img, 
                0, 0, 
                videoCanvas.value.width, 
                videoCanvas.value.height
            );
        }
        
        // 清理资源
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 检查是否有新帧需要处理
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    
    img.onerror = (e) => {
        console.error("图片加载失败:", e);
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 即使出错也继续处理下一帧
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    img.src = url;
}
// 统一的清理函数
const cleanup = () => {
  CloseCameraBtn();
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
    animationFrameId = null; // 重置为null
  }
  frameQueue = [];
  if (webSocketService) {
    // webSocketService.close();
    webSocketService = null; // 重置为null
  }
};
// 关闭后的回调事件
const closeHandle = () => {
    emit('getList', '来了来了')
}

const closeConfirm = () => {
    CloseCameraBtn();
    closewebSocketService()
    form.value = {}
    changeShowStatus()
}
// 组件卸载前的处理
onBeforeUnmount(() => {
  cleanup();
});

onUnmounted(() => {
  window.removeEventListener('beforeunload', cleanup);
});
</script>
<style>
.demo-image__error{
    border:1px solid #eee;margin-right: 10px;
}
.demo-image__error .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 49%;
  box-sizing: border-box;
  vertical-align: top;
  
}
.demo-image__error .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.demo-image__error .el-image {
  max-width: 300px;
  max-height: 200px;
  width: 100%;
  height: 200px;
}

.demo-image__error .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 16px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 16px;
}
.qianming .el-form-item__content{align-items: flex-start;}
.el-image-viewer__canvas .el-image-viewer__img{background: white;}
.el-image-viewer{position: fixed;}
</style>